package com.dimeng;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.dimeng.entity.Info;
import com.dimeng.utils.AppCache;
import com.dimeng.utils.CommonUtil;
import com.dimeng.utils.Constant;
import com.dimeng.utils.LoadDataThread;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;


/**
 * @author write by ccn<br>
 * <b>helloandroid100@gmail.com</b>
 * @version 0.1;2012-6-29 下午5:14:15<br>
 * descrition:价格行情、热门求购的视图
 */
public class PriceBuyActivity extends SuperActivity {
	private static final long serialVersionUID = -151598863829298799L;
	public  static final String URL_OR_INFOID = "urlOrInfoId";
	private static final String TITLE = "title";
	private String url;
	private String title;
	private TextView titleTV;
	private LinearLayout hotBuyTabLayout;
	private TextView firstTVTab;
	private TextView secondTVTab;
	private TextView thirdTVTab;
	private TextView firstBGTab;
	private TextView secondBGTab;
	private TextView thirdBGTab;
	
	private ListView listView;
	private int firstListViewItemPostion;
	private int itemCount;
	private List<HashMap<String,String>> cachList = new ArrayList<HashMap<String,String>>();
	private String type;//视图类型
	private SimpleAdapter adapter;
	private Resources resources;
	private Thread loadDataThread;
	private LinearLayout loadingLayout;
	private Gson gson = new Gson();
	
	private int msgWhat = -1;
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			loadingLayout.setVisibility(View.GONE);
			msgWhat = msg.what;
			switch (msg.what) {
			case 0:
            	Toast.makeText(PriceBuyActivity.this, "已加载所有数据", Toast.LENGTH_SHORT).show();
				break;
            case 1:
				String json = (String) msg.obj;
				List<HashMap<String,String>> infoLoadList = gson.fromJson(json, new TypeToken<List<HashMap<String,String>>>(){}.getType());
				List<HashMap<String,String>> currentList = AppCache.keyListMap.get(type);
				if(null == currentList)
					currentList = new ArrayList<HashMap<String,String>>();
				currentList.addAll(infoLoadList);
				AppCache.keyListMap.put(type, currentList);
				cachList.clear();
				cachList.addAll(currentList);
				adapter.notifyDataSetChanged();
				listView.setAdapter(null);
				listView.setAdapter(adapter);
				AppCache.listViewFirstPostionMap.put(type, firstListViewItemPostion+itemCount);
				listView.setSelection(AppCache.listViewFirstPostionMap.get(type));
                break;
            case 2:
            	Toast.makeText(PriceBuyActivity.this, Constant.NET_ERROR, Toast.LENGTH_LONG).show();
            	break;
            default:
            	break;
        }
		};
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		resources = getResources();
		setContentView(R.layout.public_listview);
		titleTV = (TextView) findViewById(R.id.titleLabelId);
		hotBuyTabLayout = (LinearLayout) findViewById(R.id.hotBuyTabLayoutId);
		firstTVTab = (TextView) findViewById(R.id.firstTVTabId);
		secondTVTab = (TextView) findViewById(R.id.secondTVTabId);
		thirdTVTab = (TextView) findViewById(R.id.thirdTVTabId);
		firstBGTab = (TextView) findViewById(R.id.firstBGTabId);
		secondBGTab = (TextView) findViewById(R.id.secondBGTabId);
		thirdBGTab = (TextView) findViewById(R.id.thirdBGTabId);
		listView = (ListView) findViewById(R.id.listViewId);
		Intent intent = getIntent();
		url = intent.getStringExtra("url");
		title = intent.getStringExtra("title");
		type = intent.getStringExtra("type");
		if(AppCache.LAST_BUY.equals(type))
			hotBuyTabLayout.setVisibility(View.VISIBLE);
		titleTV.setText(title);
		
		loadingLayout = CommonUtil.loadingLayout(this);
		List<HashMap<String,String>> list  = AppCache.keyListMap.get(type);
		if(null != list)
			cachList.addAll(AppCache.keyListMap.get(type));
		adapter = new SimpleAdapter(this,cachList,R.layout.public_item,
				new String[]{URL_OR_INFOID,TITLE},new int[]{R.id.hiddenItemId,R.id.itemNameId});
		listView.setAdapter(adapter);
		if(0 == cachList.size()){
			startLoadDataThread();
		}
		
		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> adapter, View view, final int position,
					long id) {
				new Thread(){
					@Override
					public void run() {
						@SuppressWarnings("unchecked")
						HashMap<String,String> selectedMap = (HashMap<String, String>) listView.getItemAtPosition(position);
						String urlOrInfoId = selectedMap.get(URL_OR_INFOID);
						Intent intent = new Intent(PriceBuyActivity.this,WebViewActivity.class);
						if(AppCache.PRICE.equals(type)){//价格行业-->属于资讯类
							String charset = Constant.CHARSET_UTF8;
							int infoId = Integer.parseInt(urlOrInfoId);
							Info info = InfoActivity.getInfoWithContentById(infoId,charset);
							intent = new Intent(PriceBuyActivity.this,BrowsePriceActivity.class);
							intent.putExtra("charset", charset);
							intent.putExtra("info", info);
							intent.putExtra("location", position);
						} else {
							intent.putExtra("url", urlOrInfoId);
						}
						PriceBuyActivity.this.startActivity(intent);
					}
				}.start();
			}
		});
		
		listView.setOnScrollListener(new OnScrollListener() {
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if(OnScrollListener.SCROLL_STATE_IDLE == scrollState || OnScrollListener.SCROLL_STATE_IDLE == scrollState){
					firstListViewItemPostion = listView.getFirstVisiblePosition();
					AppCache.listViewFirstPostionMap.put(type, firstListViewItemPostion);
				}
			}
			
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				if(1 == msgWhat && (firstVisibleItem + visibleItemCount) == totalItemCount && 0 < totalItemCount){
					itemCount = visibleItemCount;
					startLoadDataThread();
				}
			}
		});
		
		firstTVTab.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				firstTVTab.setTextColor(Color.rgb(255, 0, 0));
				secondTVTab.setTextColor(Color.rgb(0, 0, 0));
				thirdTVTab.setTextColor(Color.rgb(0, 0, 0));
				
				firstBGTab.setBackgroundColor(Color.rgb(255, 0, 0));
				secondBGTab.setBackgroundDrawable(null);
				thirdBGTab.setBackgroundDrawable(null);
				
				url = Constant.HOST_URL+resources.getString(R.string.lastBuyAction);
				type = AppCache.LAST_BUY;
				cachList.clear();
				List<HashMap<String,String>> list  = AppCache.keyListMap.get(type);
				if(null != list)
					cachList.addAll(AppCache.keyListMap.get(type));
				if(0 == cachList.size()){
					startLoadDataThread();
				}
				adapter.notifyDataSetChanged();
				listView.setSelection(AppCache.listViewFirstPostionMap.get(type));
			}
		});
		secondTVTab.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				firstTVTab.setTextColor(Color.rgb(0, 0, 0));
				secondTVTab.setTextColor(Color.rgb(255, 0, 0));
				thirdTVTab.setTextColor(Color.rgb(0, 0, 0));
				
				firstBGTab.setBackgroundDrawable(null);
				secondBGTab.setBackgroundColor(Color.rgb(255, 0, 0));
				thirdBGTab.setBackgroundDrawable(null);
				
				url = Constant.HOST_URL+resources.getString(R.string.enmergencyBuyAction);
				type = AppCache.ENMERGENCY_BUY;
				cachList.clear();
				List<HashMap<String,String>> list  = AppCache.keyListMap.get(type);
				if(null != list)
					cachList.addAll(AppCache.keyListMap.get(type));
				if(0 == cachList.size()){
					startLoadDataThread();
				}
				adapter.notifyDataSetChanged();
				listView.setSelection(AppCache.listViewFirstPostionMap.get(type));
			}
		});
		thirdTVTab.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				firstTVTab.setTextColor(Color.rgb(0, 0, 0));
				secondTVTab.setTextColor(Color.rgb(0, 0, 0));
				thirdTVTab.setTextColor(Color.rgb(255, 0, 0));
				firstBGTab.setBackgroundDrawable(null);
				secondBGTab.setBackgroundDrawable(null);
				thirdBGTab.setBackgroundColor(Color.rgb(255, 0, 0));
				
				url = Constant.HOST_URL+resources.getString(R.string.topBuyAction);
				type = AppCache.TOP_BUY;
				cachList.clear();
				List<HashMap<String,String>> list  = AppCache.keyListMap.get(type);
				if(null != list)
					cachList.addAll(AppCache.keyListMap.get(type));
				if(0 == cachList.size()){
					startLoadDataThread();
				}
				adapter.notifyDataSetChanged();
				listView.setSelection(AppCache.listViewFirstPostionMap.get(type));
			}
		});
	}
	
	/**开启下载数据的线程**/
	public void startLoadDataThread(){
		listView.setAdapter(adapter);
		if(null == loadDataThread || !loadDataThread.isAlive()){
			loadDataThread = new LoadDataThread(url,Constant.CHARSET_GBK,handler,false);
			loadDataThread.start();
			loadingLayout.setVisibility(View.VISIBLE);
		}
	}
}
